import React, { useState } from "react";
import "./index.css";
import logo from "../../../assets/icon/login_img.png";
import { Form, Input, Button, Divider, Toast } from "antd-mobile";
import mail from "../../../assets/icon/login_icon_mail_n.png";
import lock from "../../../assets/icon/login_icon_lock_n.png";
import hide from "../../../assets/icon/login_icon_hide_password_n.png";
import show from "../../../assets/icon/login_icon_show_password.png";
import weixin from "../../../assets/icon/login_icon_weixin_white_n.png";
import toHome from "../../../assets/icon/home.png";
import LoginCss from "../../../components/pages/User/LoginCss";
import { userLogin } from "../../../store/sliceReducer/UserSliceReudcer";
import { useAppDispatch } from "../../../store";
import { useAppSelector } from "../../../store";
import { useDebounce } from "../../../components/Debounce";
// RSA加密
import { JSEncrypt } from "jsencrypt";
import { useNavigate } from "react-router-dom";
import request from "../../../utils/request";
export const publicKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`;

export const encryptedData = (publicKey: string, data: string) => {
  // 新建JSEncrypt对象
  const encryptor = new JSEncrypt();
  // 设置公钥
  encryptor.setPublicKey(publicKey); // publicKey为公钥
  // 加密数据
  return encryptor.encrypt(data); //data就是需要加密的密码
};

const Index: React.FC = () => {
  const dispatch = useAppDispatch();
  // const { loginres } = useAppSelector((state) => state.user);
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [loadFlag, setloadFlag] = useState(false);
  const [form] = Form.useForm();
  const [users, setUsers] = useState({
    email: "",
    pwd: "",
  });
  // 登录
  const onSubmit = () => {
    // 判断是否为空
    if (users.email && users.pwd) {
      setloadFlag(true);
      const pwda = encryptedData(publicKey, users.pwd);
      Object.assign(users, {
        pwd: pwda,
      });
      // 登录
      request
        .post(`/api/health/user/v1/login`, users, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          console.log(res.data);
          const { message, status, result } = res.data;
          // console.log(result);

          if (status == "0000") {
            localStorage.setItem("userInfo", JSON.stringify(result));
            localStorage.setItem("token", result.jiGuangPwd);

            setTimeout(() => {
              Toast.show({
                icon: "success",
                content: message,
                duration: 1000,
                afterClose: () => {
                  setloadFlag(false);
                  navigate("/");
                },
              });
            }, 1000);
          } else {
            setloadFlag(false);
            Toast.show({
              icon: "fail",
              duration: 1500,
              content: message,
            });
          }
        });
    } else {
      //为空提示
      Toast.show({
        content: "输入不能为空",
        duration: 2000,
      });
    }
  };

  const delayedQuery = useDebounce(() => onSubmit(), 1000);
  const onChange = () => {
    delayedQuery(1);
  };
 
  return (
    <div className="user_login_box">
      <div className="toHome">
        <img src={toHome} alt="" onClick={() => navigate("/")} />
      </div>
      <div className="img_box">
        <img src={logo} alt="" />
      </div>
      <div className="loginmiddlw">
        <LoginCss>
          <div className="content">
            <Form
              layout="horizontal"
              form={form}
              onFinish={onChange}
              footer={
                <Button
                  block
                  // loading={loadFlag}
                  color="primary"
                  type="submit"
                  size="large"
                >
                  登录
                </Button>
              }
            >
              <Form.Item>
                <div className="icon">
                  <img src={mail} className="mailimg" alt="" />
                </div>
                <Input
                  onChange={(e) =>
                    setUsers({
                      ...users,
                      email: e,
                    })
                  }
                  placeholder="请输入邮箱"
                />
              </Form.Item>
              <Form.Item
                extra={
                  <div>
                    {visible ? (
                      <img
                        src={show}
                        style={{ width: "30px", height: "24px" }}
                        onClick={() => setVisible(false)}
                        alt=""
                      />
                    ) : (
                      <img
                        src={hide}
                        style={{ marginRight: "3px" }}
                        onClick={() => setVisible(true)}
                        alt=""
                      />
                    )}
                  </div>
                }
              >
                <div className="icon">
                  <img src={lock} className="lockimg" alt="" />
                </div>
                <Input
                  onChange={(e) =>
                    setUsers({
                      ...users,
                      pwd: e,
                    })
                  }
                  placeholder="请输入密码"
                  type={visible ? "text" : "password"}
                />
              </Form.Item>
            </Form>
          </div>
        </LoginCss>
        {/* 底部 */}
        <div className="login_btn">
          <div>忘记密码</div>
          <div>
            <span>暂无账号？</span>
            <span className="rigister" onClick={() => navigate("/register")}>
              立即注册
            </span>
          </div>
        </div>
      </div>

      <div className="login_bot">
        <div className="divider">
          <Divider style={{ borderColor: "#fff", color: "#fff" }}>
            其他登录方式
          </Divider>
        </div>
        <div>
          <img src={weixin} alt="" />
        </div>
      </div>
    </div>
  );
};

export default Index;
